package com.foreknow.dao.impl;

import com.foreknow.bean.GuestBook;
import com.foreknow.dao.GuestBookDao;
import com.foreknow.mapping.EntityMapping;
import com.foreknow.mapping.MappingFactory;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class GuestBookDaoImpl extends BaseDao implements GuestBookDao {

    @Override
    public boolean addBook(GuestBook guestBook) throws SQLException {
        String sql = "insert into guestbook (name, phone, email, title, content, createdtime) values (?,?,?,?,?,?)";
        int isRight = jdbcTemplate.update(sql,guestBook.getName(),guestBook.getPhone(),guestBook.getEmail(),guestBook.getTitle(),guestBook.getContent(),guestBook.getCreatedtime());
        return isRight == 1;
    }

    @Override
    public boolean deleteBook(Integer ID) throws SQLException {
        String sql = "delete from guestbook where id = ?";
        int isRight = jdbcTemplate.update(sql,ID);
        return isRight == 1;
    }

    @Override
    public GuestBook selectById(Integer id) throws SQLException {
        String sql = "select * from guestbook where id=?";
        EntityMapping mapping = mappingFactory.getMap(MappingFactory.GUESTBOOK_MAPPING);
        List<Object>bookList = jdbcTemplate.query(sql,mapping,id);
        if (bookList.size()>0){
            GuestBook guestBook = (GuestBook) bookList.get(0);
            return guestBook;
        }
        return null;
    }

    @Override
    public boolean updateBook(GuestBook guestBook, String name, String phone, String email, String title, String content, String createdTime) throws SQLException {
        String sql = "update guestbook set name=?,phone=?,email=?,title=?,content=?,createdtime=? where id = ?";
        int isRight = jdbcTemplate.update(sql, name, phone, email, title, content, createdTime, guestBook.getID());
        return isRight == 1;
    }

    @Override
    public List<Object> showAllBook() throws SQLException {
        String sql = "select * from guestbook";
        EntityMapping mapping = mappingFactory.getMap(MappingFactory.GUESTBOOK_MAPPING);
        List<Object>bookList = jdbcTemplate.query(sql,mapping);
        return bookList;
    }

    @Override
    public List<Object> selectBook(String name) throws SQLException {
        String sql = "select * from guestbook where name like '%"+name+"%'";
        EntityMapping mapping = mappingFactory.getMap(MappingFactory.GUESTBOOK_MAPPING);
        List<Object>bookList = jdbcTemplate.query(sql,mapping);
//        List<GuestBook>bookList = new ArrayList<>();
//        Iterator<Object> iterator = list.iterator();
//        while (iterator.hasNext()){
//            GuestBook guestBook = (GuestBook) iterator.next();
//            bookList.add(guestBook);
//        }
        return bookList;
    }
}
